package com.java.IO.buffered_stream;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Arrays;

public class BufferedReaderAPI {
    // 读取纯文本类型文件内的所有内容。换行符只适用于Windows
    public static StringBuilder readAllContentsOfFile(String path) throws Exception {
        try (BufferedReader bufferedReader = new BufferedReader(new FileReader(path))) {
            StringBuilder resultChars = new StringBuilder();
            
            String str = "";
            while ((str = bufferedReader.readLine()) != null) {
                resultChars.append(str + "\r\n");
            }
            return resultChars;
        } catch (FileNotFoundException e) {
            throw new Exception("路径错误，请检查路径是否存在或正确。错误信息为" + e.getMessage());
        }
    }
    
    public static void main(String[] args) throws Exception {
        String path = "File和IO流\\com\\java\\files\\char_stream.txt";
        
        // 创建对象：创建规则主要依赖于构造形参Reader的子类
        BufferedReader bufferedReader = new BufferedReader(new FileReader(path));
        
        // read：读取目标地内数据，若无参数则一次读取一字符，若无数据则返回-1。若参数为字符数组且有数据则一次性读取字符数组长度的字符并存于该字符数组内同时返回读取到的字符长度
        System.out.println(bufferedReader.read()); // 97
        System.out.println(bufferedReader.read()); // 57
        System.out.println(bufferedReader.read()); // 20013 (十进制数)
        System.out.println((char) bufferedReader.read()); // 中 (强转)
        System.out.println(bufferedReader.read()); // 13
        System.out.println(bufferedReader.read()); // 10
        char[] chars = new char[14];
        System.out.println(bufferedReader.read(chars, 12, 2)); // 2
        System.out.println(Arrays.toString(chars)); // [ ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  , a, 哈] (读取2个数据到数组指定位置12)
        System.out.println(bufferedReader.read(chars)); // 14
        System.out.println(Arrays.toString(chars)); // [c, d, d, e, 啊, 啊, 啊, H, e, l, l, o, H, e]
        
        // readLine：读取目标地内一行数据，若无数据则返回null。注意回车换行符读不到
        System.out.println(bufferedReader.readLine()); // 换行(Windows\r\n、Linux\n、Mac\r)
        System.out.println(bufferedReader.readLine()); // null
        
        // close：关闭流并释放资源
        bufferedReader.close();
        
        // 读取文件内的所有内容，路径必须为文件路径
        System.out.println(readAllContentsOfFile(path)); // a9中中\r\na哈cdde啊啊啊HelloHe\r\n
    }
}
